package com.chensheng.controller;

import com.chensheng.enums.ResultErrorEnum;
import com.chensheng.exception.SellException;
import com.chensheng.model.OrderMaster;
import com.chensheng.service.OrderMasterService;
import com.chensheng.service.PayService;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * @Author:ChenSheng
 * @Description:
 * @Date: Created in 下午 16:44 2018/5/16 0016
 */
@Controller
@Slf4j
public class PayController {

    @Autowired
    OrderMasterService orderMasterService;

    @Autowired
    private PayService payService;

    @GetMapping("/pay")
    @ResponseBody
    public ModelAndView index(@RequestParam("openid") String openid,
                              @RequestParam("orderId") String orderId,
                              @RequestParam("returnUrl") String returnUrl,
                              Map<String, Object> map) {
        log.info("【微信支付】发起支付，orderId={}", orderId);
        log.info("【微信支付】发起支付，openid={}", openid);
        //log.info("returnUrl={}", returnUrl);

        //String orderId = "15265195357417196817";
        OrderMaster orderMaster = orderMasterService.findOneByOrderId(orderId);
        if(orderMaster == null){
            log.error("【支付订单】Errors:{}", ResultErrorEnum.ORDER_NOT_EXIST_ERROR.getMsg());
            throw new SellException(ResultErrorEnum.ORDER_NOT_EXIST_ERROR);
        }

        orderMaster.setBuyerOpenid(openid);
        PayResponse payResponse = payService.create(orderMaster);

        map.put("payResponse", payResponse);
        //returnUrl = "http://www.baidu.com";
        returnUrl = "http://sell.com/#/order/" + orderId;
        log.info("【微信支付】发起支付，returnUrl={}", returnUrl);
        map.put("returnUrl", returnUrl);

        return new ModelAndView("/pay", map);
    }

    @PostMapping("/pay/notify")
    public ModelAndView notify(@RequestBody String notifyData) {

        payService.notify(notifyData);
        log.info("【微信支付】异步通知：success");

        return new ModelAndView("pay/success");
    }
}
